#!/usr/bin/env python
#-*- coding: utf-8 -*-
# AUTHOR: guangling.hou@gmail.com
# FILENAME: py_urlencode.py
# CREATED: 2014-02-10 13:38
# MODIFIED: 2014-02-10 18:26
# Description: 

import urllib
import py_decode

class UrlEncoder():
	def __init__(self):
		self._decoder = py_decode.PY_Decode()

	def get_encode_uri(self,Uri,fields):

		if not Uri:
			raise DM_InputError('Uri is None')

		f = {}
		for k,v in fields.items():
			f[self._decoder.decode(str(k)).encode('utf-8')] = \
					self._decoder.decode(str(v)).encode('utf-8')

		try:
			field_str = urllib.urlencode(f)
		except Exception,e:
			raise DM_InputError(str(e))
		

		try:
			return (Uri[-1] == '?' and [Uri + field_str] or [Uri + '?' + field_str])[0]
		except Exception,e:
			raise DM_InputError(str(e))
			

if __name__ == '__main__':
	urlencoder = UrlEncoder()

	#f = {'a':'asdfa','你好'.decode('utf-8'):'sdfasdf'}
	f = {'a':'asdfa','你好':'sdfasdf',10:100}
	print urlencoder.get_encode_uri('http://www.163.com',f)
